package com.ubb.damate.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ubb.damate.beans.UserSessionBean;
import com.ubb.damate.jasper.report.ReportType;
import com.ubb.damate.model.ReportModel;

@ManagedBean
public class ReportController {

	private static final Log log = LogFactory.getLog(ReportController.class);
	
	@ManagedProperty(value = "#{report}")
	private ReportModel reportModel;
	
	@ManagedProperty(value = "#{userSession}")
	private UserSessionBean userSessionBean;

	public ReportModel getReportModel() {
		return reportModel;
	}

	public void setReportModel(ReportModel reportModel) {
		this.reportModel = reportModel;
	}

	public UserSessionBean getUserSessionBean() {
		return userSessionBean;
	}

	public void setUserSessionBean(UserSessionBean userSessionBean) {
		this.userSessionBean = userSessionBean;
	}

	public String generateReport() {
		DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
        Date date = new Date();
		
		String generatedFileName = "report_" + (dateFormat.format(date)) + ".pdf";
		ReportType reportType = ReportType.valueOf(reportModel.getReportType());
		
		ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ectx.getRequest();
		request.setAttribute("fileName", generatedFileName);
		request.setAttribute("reportType", reportType);
		HttpServletResponse response = (HttpServletResponse) ectx.getResponse();
		RequestDispatcher dispatcher = request.getRequestDispatcher("/generateReport");
		try {
			dispatcher.forward(request, response);
			FacesContext.getCurrentInstance().responseComplete();
		} catch (ServletException e) {
			log.error("ERROR: "+e.getMessage(),e);
		} catch (IOException e) {
			log.error("ERROR: "+e.getMessage(),e);
		}
		return null;
	}
	
	public String selectReport() {
		userSessionBean.setCurrentPage("/WEB-INF/content/report/reportdisplay.xhtml");
		reportModel.setReportType(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("reportType"));
		return null;
	}
}